package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IFollowService followService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public Result findById(Long id) {
        //查询博客
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在！");
        }
        //获取博主信息
        Long blogUserId = blog.getUserId();
        User user = userService.getById(blogUserId);
        if (user == null) {
            return Result.fail("博主不存在！");
        }
        //设置博客中 博主昵称、头像
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        //redis查询是否点赞过
        boolean liked = isLiked(id);
        //设置用户是否点赞
        blog.setIsLike(liked);


        return Result.ok(blog);

    }

    /**
     * 点赞或取消点赞
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //当前用户
        Long userId = UserHolder.getUser().getId();

        String key = "blog:like:"+id;
        //判断是否点赞过
        boolean liked = isLiked(id);
        //没点过赞
        if(!liked){
            //更新博客点赞数 加1
            boolean success = update().setSql("liked = liked+1").eq("id", id).update();

            //加入缓存
            if(success) {
                redisTemplate.opsForZSet().add(key, userId,System.currentTimeMillis());
            }
        }else{
            //更新博客点赞数 减1
            boolean success = update().setSql("liked = liked-1").eq("id", id).update();

            //从缓存中移除
            if(success) {
                redisTemplate.opsForZSet().remove(key, userId);
            }
        }

        return Result.ok();
    }

    /**
     * 用户是否点赞过
     * @param id 博客id
     * @return
     */
    public boolean isLiked(Long id){
        //当前用户
        Long userId = UserHolder.getUser().getId();

        String key = "blog:like:"+id;
        //判断是否点赞过
        Double score = redisTemplate.opsForZSet().score(key, userId);

        return score==null ? false : true;
    }

    /**
     * 查询热门博客
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            boolean liked = isLiked(blog.getId());
            blog.setIsLike(liked);
        });
        return Result.ok(records);
    }


    /**
     * 点赞列表
     * @param id
     * @return
     */
    @Override
    public Result queryLikes(Long id) {

        String key = "blog:like:"+id;
        //获取点赞用户ids
        Set<Long> top5Ids = redisTemplate.opsForZSet().range(key, 0, 4);

        //判断是否有人点赞

        //1.没有
        if (top5Ids == null || top5Ids.isEmpty()) {
            // 返回空集合
            return Result.ok(Collections.emptyList());
        }
        //2.有
        // 转成集合
        List<Long> ids = new ArrayList<>(top5Ids);

        //查库
        List<User> userList = userMapper.list(ids);
        //stream流封装
        List<UserDTO> userDTOs = userList.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

//        List<UserDTO> userDTOList = new ArrayList<>();
//        for (User user :userList) {
//            //封装
//            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//            userDTOList.add(userDTO);
//        }
        return Result.ok(userDTOs);
    }

    /**
     * 保存博客
     * 推送给所有粉丝
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());

        // 保存探店博文
        boolean success = save(blog);
        if(!success) {
            return Result.fail("保存博文失败！");
        }
        //查询所有粉丝
        List<Follow> fans = followService.query()
                .eq("follow_user_id", user.getId()).list();

        if(fans !=null && fans.size()>0) {
            //推送 写入redis
            for (Follow fan : fans) {
                Long userId = fan.getUserId();
                String key = "feed:" + userId;
                redisTemplate.opsForZSet().add(key, blog.getId(), System.currentTimeMillis());
            }
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 滚动查询关注博主的博客
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBolgOfFollow(Long max, Integer offset) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();

        //redis查询用户关注的博客
        String key = "feed:"+userId;

        //默认返回升序结果，但需要降序
        //参数 ：key 、最小值（不关心）、 最大值、 偏移量、每页数据量
        Set<ZSetOperations.TypedTuple<Integer>> set = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(set==null || set.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        //解析数据

        Long minTime = 0L;
        offset = 0;
        List blogIds = new ArrayList<>();
        for ( ZSetOperations.TypedTuple<Integer> tuple:set) {
            //1.获取最后一条的时间戳
            minTime = tuple.getScore().longValue();
            //获取博客ids
            Integer blogId = tuple.getValue();
            blogIds.add(blogId);
        }
        //2.获取偏移量  和返回的最后一条数据时间戳一样的数据个数
        for ( ZSetOperations.TypedTuple<Integer> tuple:set) {
            if(minTime == tuple.getScore().longValue()) {
                offset += 1;
            }
        }
        //3.查询所有博客
        List<Blog> blogList = blogMapper.list(blogIds);


        //封装返回
        // 博客列表数据、最后一条数据的时间戳、偏移量
        ScrollResult sr = new ScrollResult();
        sr.setOffset(offset);
        sr.setMinTime(minTime);
        sr.setList(blogList);

        return Result.ok(sr);


    }
}
